<template>
  <basic-layout>
    <div class="home">
      <h1>热门推荐</h1>
      <div v-if="loading" class="loading">
        加载中...
      </div>
      <div v-else-if="error" class="error">
        {{ error }}
      </div>
      <div v-else class="book-list">
        <div v-for="book in books" 
             :key="book.id" 
             class="book-item"
             @click="goToDetail(book.id)">
          <img :src="book.cover" :alt="book.title">
          <h3 class="ellipsis-2">{{ book.title }}</h3>
          <div class="book-info">
            <span class="category">{{ book.category }}</span>
            <!-- <span class="price">¥{{ book.price }}</span> -->
             <span class="author">{{ book.author }}</span>
          </div>
        </div>
      </div>
    </div>
  </basic-layout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { bookApi } from '@/api/apis/book'

const router = useRouter()
const books = ref([])
const loading = ref(false)
const error = ref('')

// 获取热门书籍数据
const fetchHotBooks = async () => {
  loading.value = true
  error.value = ''
  
  try {
    const res = await bookApi.getHotBooks({ limit: 10 })
    console.log('获取热门书籍成功:', res)
    if (res.code === 200) {
      books.value = res.data.list
    } else {
      error.value = res.message
    }
  } catch (err) {
    error.value = '获取数据失败，请稍后重试'
    console.error('获取热门书籍失败:', err)
  } finally {
    loading.value = false
  }
}

// 跳转到书籍详情
const goToDetail = (id) => {
  router.push(`/books/${id}`)
}

// 页面加载时获取数据
onMounted(() => {
  fetchHotBooks()
})
</script>

<style scoped lang="scss">
.home {
  padding: 20px;

  h1 {
    margin-bottom: 20px;
    color: #333;
  }

  .loading,
  .error {
    text-align: center;
    padding: 40px;
    color: #666;
  }

  .book-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
    margin-top: 20px;
  }

  .book-item {
    text-align: left;
    background: #fff;
    border-radius: 8px;
    padding: 10px;
    cursor: pointer;
    transition: transform 0.2s;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);

    &:hover {
      transform: translateY(-5px);
    }
    
    img {
      width: 100%;
      height: 280px;
      object-fit: cover;
      border-radius: 8px;
    }

    h3 {
      margin: 10px 0 5px;
      font-size: 16px;
      color: #333;
    }

    p {
      color: #666;
      font-size: 14px;
    }

    .book-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 10px;
      padding-top: 10px;
      border-top: 1px solid #eee;

      .category {
        color: #42b983;
        font-size: 12px;
      }

      .price {
        color: #f56c6c;
        font-weight: bold;
      }
      .author {
        font-size: 12px;
      }
    }
  }
}
</style>